package com.xyzh05.webapp.action;

import com.opensymphony.xwork2.Preparable;
import com.xyzh05.service.TransactionManager;
import com.xyzh05.util.PageBean;
import com.xyzh05.model.Transaction;
import com.xyzh05.webapp.action.BaseAction;

import java.util.List;

public class TransactionAction extends BaseAction implements Preparable {
    private TransactionManager transactionManager;
    private List<Transaction> transactions;
    private PageBean pageBean;
    private Transaction transaction;
    private Long id;
    private String query;

    public void setTransactionManager(TransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }
    
    

    public List<Transaction> getTransactions() {
        return transactions;
    }

    public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	public TransactionManager getTransactionManager() {
		return transactionManager;
	}

	public void setTransactions(List<Transaction> transactions) {
		this.transactions = transactions;
	}

	/**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String transactionId = getRequest().getParameter("transaction.id");
            if (transactionId != null && !transactionId.equals("")) {
                transaction = transactionManager.get(new Long(transactionId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
    	pageBean = transactionManager.findList(pageBean, transaction);
    	return "list" ; 
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Transaction getTransaction() {
        return transaction;
    }

    public void setTransaction(Transaction transaction) {
        this.transaction = transaction;
    }

    public String delete() {
        transactionManager.remove(transaction.getId());
        saveMessage(getText("transaction.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            transaction = transactionManager.get(id);
        } else {
            transaction = new Transaction();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (transaction.getId() == null);

        transactionManager.save(transaction);

        String key = (isNew) ? "transaction.added" : "transaction.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}